package com.ebring.shareEducation.controller;

import com.ebring.shareEducation.utils.CodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@CrossOrigin(origins = "http://wangliang.vipgz1.idcfengye.com", maxAge = 3600)
@Api(value = "登录验证码" ,tags = {"登录验证码"})
public class VerificationCodeController {

    @Autowired
    private StringRedisTemplate template;

    @GetMapping("/user/getCode")
    @ApiOperation(value="生成验证码", notes="生成验证码")
    public void getCode(HttpServletResponse response) {

        // 调用工具类生成的验证码和验证码图片
        Map<String, Object> codeMap = CodeUtils.generateCodeAndPic();

        // 将四位数字的验证码保存到redis中。
        template.opsForValue().set(codeMap.get("code").toString().toUpperCase(), codeMap.get("code").toString().toUpperCase(), 10 * 60, TimeUnit.SECONDS);

        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1);
        response.setContentType("image/jpeg");

        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos;
        try {
            sos = response.getOutputStream();
            ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
